package org.bing.zion.filter.logging;

import java.io.IOException;
import java.nio.ByteBuffer;

import org.bing.engine.common.logging.Log;
import org.bing.engine.common.logging.LogFactory;
import org.bing.zion.core.ProtocolFilterAdapter;
import org.bing.zion.core.ProtocolFilterChain;
import org.bing.zion.core.Session;


public class LoggingFilter extends ProtocolFilterAdapter {
	private static final Log logger = LogFactory.getLog(LoggingFilter.class);
	private String prefix;

	public LoggingFilter() {
		prefix = "";
	}

	public LoggingFilter(String prefix) {
		this.prefix = "<" + prefix + ">";
	}

	@Override
	public void messageReceived(ProtocolFilterChain chain, Session session, Object msg) throws IOException {
		if (msg instanceof ByteBuffer) {
			ByteBuffer buf = (ByteBuffer) msg;
			ByteBuffer tmp = buf.duplicate();
			tmp.flip();
			byte[] bs = new byte[tmp.limit()];
			tmp.get(bs);
			logger.info(prefix + " RECV " + new String(bs));
		} else {
			logger.info(prefix + " RECV " + msg);
		}

		// goon other filter
		super.messageReceived(chain, session, msg);
	}

	@Override
	public void messageSent(ProtocolFilterChain chain, Session session, Object msg) throws IOException {
		if (msg instanceof ByteBuffer) {
			ByteBuffer buf = (ByteBuffer) msg;
			ByteBuffer tmp = buf.duplicate();
			// tmp.flip();
			byte[] bs = new byte[tmp.limit()];
			tmp.get(bs);
			logger.info(prefix + " SENT " + new String(bs));
		} else {
			logger.info(prefix + " SENT " + msg);
		}

		// goon other filter
		super.messageSent(chain, session, msg);
	}

}
